import Vue from 'vue'
import VueRouter from 'vue-router'


import login from '@/views/user/login.vue'
import home from '@/views/home/home.vue'
import qa from '@/views/qa/qa.vue'
import user from '@/views/user/user.vue'
import movie from '@/views/movie/movie.vue'
import layout from '@/views/layout.vue'
import notfound from '@/views/notfound/notfound.vue'
import edit from '@/views/user/edit.vue'


Vue.use(VueRouter)

const routes = [
  {
    name:'login',
    path:'/login',
    component:login
  },
  {
    name:'edit',
    path:'/edit',
    component:edit
  },
  {
    name:'layout',
    path:'/',
    component:layout,
    children:[
      {
        name:'home',
        path:'/home',
        component:home
      },
      {
        name:'movie',
        path:'/movie',
        component:movie
      },
      {
        name:'qa',
        path:'/qa',
        component:qa
      },
      {
        name:'user',
        path:'/user',
        component:user,
        meta:{
          isLogin:true
        }
      },
      {
        path:'/',
        redirect:'/home'
      }
    ]
  },
  {
    name:'notfound',
    path:'/notfound',
    component:notfound
  },
  {
    /* 
   (1) * : 任意路径重定向到notfound
   (2)路由默认从上往下匹配的，如果可以匹配到则跳转页面。无法匹配则继续往下匹配直到所有路由匹配结束
    */
    path: '*',
    redirect: '/notfound'
  }

]

const router = new VueRouter({
  routes
})

import { getToken } from '@/utils/token.js'
import { Toast } from 'vant';

router.beforeEach((to,from,next)=>{
  // console.log('to:',to);
  // console.log('from:',from);
  if(to.meta.isLogin){
    if(getToken()){
      next()
    }else{
      Toast.fail('请登录')
      next('/login')
    }
  }else{
    next()
  }
})

export default router

